package com.ezgo.erc.controller;

import java.io.File;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.ezgo.erc.master.utils.GlobeStatus;
import com.ezgo.erc.master.utils.Message;

/**
 * 
 * (文件系统)模块 TODO(文件管理控制器)
 * 
 * @author devintam
 * @date 2016年1月20日 下午3:47:54
 *
 */
@Controller
@RequestMapping("/fastdfs")
public class FastDFSController extends BaseController {
	private static final String fdfs_file_path = "\\config\\properties\\fdfs_client.conf";

	@ResponseBody
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public Message<String> upload(@RequestParam MultipartFile file) {
		Message<String> res = new Message<String>();
		try {
			if (file.isEmpty()) {
				res.setStatus(GlobeStatus.API_NOT_FOUND.statusCode);
				res.setMsg(GlobeStatus.API_NOT_FOUND.zhStatusMsg);
			} else {
				logger.info("FastDFSController-upload-request-file=" + file.getOriginalFilename());
				String tempFileName = file.getOriginalFilename();
				ClientGlobal.init(getFdfsFilePath());
				byte[] fileBuff = file.getBytes();
				String fileId = "";

				// 建立连接
				TrackerClient tracker = new TrackerClient();
				TrackerServer trackerServer = tracker.getConnection();
				StorageServer storageServer = null;
				StorageClient1 client = new StorageClient1(trackerServer, storageServer);

				// 设置元信息
				NameValuePair[] metaList = new NameValuePair[3];
				metaList[0] = new NameValuePair("fileName", tempFileName);
				metaList[1] = new NameValuePair("authorName", "devintam");
				metaList[2] = new NameValuePair("fileLength", String.valueOf(file.getSize()));

				// 上传文件
				fileId = client.upload_file1(fileBuff, tempFileName.substring(tempFileName.lastIndexOf(".") + 1), metaList);
				res.setData(fileId);

				res.setStatus(GlobeStatus.API_OK.statusCode);
				res.setMsg(GlobeStatus.API_OK.zhStatusMsg);
			}

			logger.info("FastDFSController-upload-response-" + JSON.toJSONString(res));
		} catch (Exception e) {
			res.setStatus(GlobeStatus.API_INTER_ERROR.statusCode);
			res.setMsg(GlobeStatus.API_INTER_ERROR.zhStatusMsg);
			logger.error("FastDFSController-upload-error" + e.getMessage());
		}
		return res;
	}

	@ResponseBody
	@RequestMapping(value = "/download", method = RequestMethod.POST)
	public Message<String> download(@RequestParam(value = "fileId", required = true) String fileId, String downPath) {
		Message<String> res = new Message<String>();
		try {
			logger.info("FastDFSController-download-request-fileId=" + fileId);

			// fastDFS方式
			ClientGlobal.init(getFdfsFilePath());

			// 建立连接
			TrackerClient tracker = new TrackerClient();
			TrackerServer trackerServer = tracker.getConnection();
			StorageServer storageServer = null;
			StorageClient1 client = new StorageClient1(trackerServer, storageServer);

			// 下载文件
			int result = client.download_file1(fileId, downPath);

			res.setData(result == 0 ? "下载成功" : "下载失败");
			res.setStatus(GlobeStatus.API_OK.statusCode);
			res.setMsg(GlobeStatus.API_OK.zhStatusMsg);
			logger.info("FastDFSController-download-response-" + JSON.toJSONString(res));
		} catch (Exception e) {
			res.setStatus(GlobeStatus.API_INTER_ERROR.statusCode);
			res.setMsg(GlobeStatus.API_INTER_ERROR.zhStatusMsg);
			logger.error("FastDFSController-download-error-" + e.getMessage());
		}
		return res;
	}

	@ResponseBody
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public Message<String> delete(@RequestParam(value = "fileId", required = true) String fileId) {
		Message<String> res = new Message<String>();
		try {
			logger.info("FastDFSController-delete-request-fileId=" + fileId);

			// fastDFS方式
			ClientGlobal.init(getFdfsFilePath());

			// 建立连接
			TrackerClient tracker = new TrackerClient();
			TrackerServer trackerServer = tracker.getConnection();
			StorageServer storageServer = null;
			StorageClient1 client = new StorageClient1(trackerServer, storageServer);
			// 下载文件
			res.setData(client.delete_file1(fileId) == 0 ? "删除成功" : "删除失败");
			res.setStatus(GlobeStatus.API_OK.statusCode);
			res.setMsg(GlobeStatus.API_OK.zhStatusMsg);
			logger.info("FastDFSController-delete-response-" + JSON.toJSONString(res));
		} catch (Exception e) {
			res.setStatus(GlobeStatus.API_INTER_ERROR.statusCode);
			res.setMsg(GlobeStatus.API_INTER_ERROR.zhStatusMsg);
			logger.error("FastDFSController-delete-error" + e.getMessage());
		}
		return res;
	}

	/**
	 * 
	 * TODO(获取当前文件路径)
	 *
	 * @return String
	 * @throws Exception
	 */
	private String getFdfsFilePath() throws Exception {
		String fdfsFilePath = new File(FastDFSController.class.getResource("/").getFile()).getCanonicalPath();
		String envStr = System.getProperty("file.separator");
		fdfsFilePath = fdfsFilePath + fdfs_file_path;
		if ("/".equals(envStr)) {
			fdfsFilePath = fdfsFilePath.replace("\\", "/");
		} else if ("\\".equals(envStr)) {
			fdfsFilePath = fdfsFilePath.replace("/", "\\");
		}
		return fdfsFilePath;
	}
}
